<template>
	<div class="app">
		<div class="status">当前状态：{{ isConnected ? '已连接' : '未连接' }}</div>
		<div class="connect button" @click="connectOrDisconnect">{{ isConnected ? '断开' : '连接' }}</div>
		<div class="send-box">
			<input type="text" v-model="sendContent"/>
			<div class="send-button button" @click="send">发送</div>
		</div>
	</div>
</template>

<script setup>
import { ref } from 'vue';

// 当前连接状态
const isConnected = ref(false);
// 当前使用的WebSocket对象
let webSocket = undefined;
// 待发送的内容
const sendContent = ref('');

/**
 * 建立一个WebSocket连接
 * @param path 连接路径
 */
const createWebSocket = (path) => {
	// 实例化一个WebSocket对象，实例化之后，会立即连接
	webSocket = new WebSocket('ws://' + location.host + path);
	// 添加各个监听事件
	webSocket.addEventListener('open', (e) => {
		isConnected.value = true;
		console.log('已连接！');
	});
	webSocket.addEventListener('close', (e) => {
		isConnected.value = false;
		console.log('已断开连接！');
	});
	webSocket.addEventListener('error', (e) => {
		console.error('出现错误！');
		console.error(e);
	});
	webSocket.addEventListener('message', (e) => {
		console.log('收到消息：' + e.data);
	});
};

/**
 * 连接或者断开连接
 */
const connectOrDisconnect = () => {
// 如果已连接则点击按钮断开连接
	if (isConnected.value) {
		// close方法关闭连接
		// 传入状态码1000表示正常关闭
		webSocket.close(1000);
	} else {
		createWebSocket('/ws/text');
	}
};

/**
 * 发送内容
 */
const send = () => {
	if (isConnected.value) {
		webSocket.send(sendContent.value);
	}
};
</script>

<style lang="scss">
.app {
	.status {
		margin-bottom: 10px;
	}

	.button {
		width: 42px;
		height: 28px;
		line-height: 28px;
		text-align: center;
		color: white;
		background-color: blue;
		border-radius: 6px;
		cursor: pointer;
		user-select: none;

		&:hover {
			background-color: purple;
		}
	}

	.send-box {
		display: flex;
		margin-top: 10px;

		.send-button {
			margin-left: 8px;
		}
	}
}
</style>